package com.liziba.demo.slice;

import com.liziba.demo.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    /** 段子存放 */
    String[] pieces;
    /** 按钮控件，切换段子 */
    Button button;
    /** 文本控件，展示段子 */
    Text text;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 根据id获取文本控件
        text = (Text) this.findComponentById(ResourceTable.Id_text);
        // 根据id获取按钮控件
        button = (Button) this.findComponentById(ResourceTable.Id_button);
        // 设置单击监听事件
        button.setClickedListener(this);

        this.getPieces();
    }



    @Override
    public void onClick(Component component) {

        if (component.getId() == ResourceTable.Id_button) {
            Random random = new Random();
            int i = random.nextInt(pieces.length);
            String piece = pieces[i];
            text.setText(piece);
        }
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }


    /**
     * 段子获取
     */
    private void getPieces() {
        // 读取段子存放于content
        StringBuilder content = new StringBuilder();
        Resource resource;
        BufferedReader br = null;
        try{
            // 通过getResourceManager获取资源文件，资源文件（文本类）的存放目录在resources -> profile
            resource = this.getResourceManager().getResource(ResourceTable.Profile_piece);
            br = new BufferedReader(new InputStreamReader(resource));
            String line;
            while ((line = br.readLine()) != null) {
                content.append(line);
            }
            // 按照---切割段子
            if (content != null) {
                pieces = content.toString().split("---");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } finally {
            // finally中关闭资源
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
